-module(cloap_esb).
-export([init/2]).
-include("cloap_record.hrl").


init(Req, Opts) ->
    Method   = cowboy_req:method(Req),
    Path     = string:join([binary_to_list(X) || X <- cowboy_req:path_info(Req)], "/"),
    AppId    = cowboy_req:binding(appid, Req),
    Url      = string:join([uddi_url(cowboy_req:binding(appid, Req)), Path], "/"),
    _Query   = cowboy_req:parse_qs(Req),
    {ok, Body, _Req} = cowboy_req:body_qs(Req),

    LoginUser = case cloap_app:use_sso() of
                    false -> <<"system">>;
                    true ->
                        {LoginUser1, _} = cowboy_cas_client:user(Req),
                        LoginUser1
                end,


    Request = case Method of
                  <<"GET">> ->
                      cloap_event:action(LoginUser, AppId, iolist_to_binary([<<"GET">>, " ", Url]), <<>>),
                      {Url, []};
                  <<"POST">> ->
                      [{Body1, true}] = Body,
                      cloap_event:action(LoginUser, AppId, iolist_to_binary([<<"POST">>, " ", Url]), Body1),
                      {Url, [], "text/plain;charset=UTF-8", Body1};
                  <<"DELETE">> ->
                      cloap_event:action(LoginUser, AppId, iolist_to_binary([<<"DELETE">>, " ", Url]), <<>>),
                      {Url, []}
        end,


    Result1 = httpc:request(method_to_atom(Method), Request, [], []),

    Req2 = case Result1 of
            {error, Reason} ->
                cowboy_req:reply(400, [], <<Reason/binary>>, Req);
            {ok, {_Status, _Headers, Result}} ->
                cowboy_req:reply(200, [{<<"content-type">>, <<"text/plain; charset=utf-8">>}], Result, Req)
            end,

    {ok, Req2, Opts}.



method_to_atom(Method) when is_binary(Method) ->
    list_to_atom(string:to_lower(binary_to_list(Method))).

uddi_url(AppId) ->
    [App] = cloap_store:find(uddi, AppId),
    case App#uddi.url of
        V when is_binary(V) -> binary_to_list(V);
        V -> V
    end.
